import Taro from '@tarojs/taro';
import dayjs from 'dayjs';
import * as fs from 'expo-file-system';

let hasLogFile = false;
const logsDirPath = `${fs.cacheDirectory || ''}logs`;
let filePath = logsDirPath + '/log-' + dayjs().format('YYYY-MM-DD') + '-1.txt';

// 因expo-file-system不支持追加写入文件，所以要做日志切分
// 监听页面跳转+页面参数
// 监听网络
export const initAppLog = async () => {
  try {
    console.log('initAppLog start', logsDirPath, filePath);
    await fs.makeDirectoryAsync(logsDirPath).catch(e => e);
    // 创建文件夹成功或已存在，下一步创建文件
    const cacheFileName = await Taro.getStorage({ key: 'log-file-name' }).catch(e => e);
    if (cacheFileName?.data) {
      const str: string = cacheFileName.data;
      if (str.includes(dayjs().format('YYYY-MM-DD'))) {
        filePath = cacheFileName.data;
      }
    }
    const { exists } = await fs.getInfoAsync(filePath);
    if (!exists) {
      await fs.writeAsStringAsync(filePath, '', { encoding: 'utf8' });
      console.log('创建日志文件', filePath);
    } else {
      logStr = await getLogText();
    }
    hasLogFile = true;
    console.log('initAppLog success');
  } catch (error) {
    console.error('Error creating folder:', error);
    Taro.showToast({
      title: 'Error creating folder: 创建日志文件夹失败',
      icon: 'none',
    });
  }
};

let logStr = '';
export const log = (data: any) => {
  logStr += '\n' + dayjs().format('YYYY-MM-DD HH:mm:ss') + ' ' + JSON.stringify(data);
  // 添加到本地text日志
  saveLogToText();
};

const saveLogToText = async () => {
  if (!hasLogFile || !logStr.length) return;
  await fs.writeAsStringAsync(filePath, logStr, { encoding: 'utf8' });
  if (logStr.length > 800000) {
    // 创建新的日志文件
    const num = Number(filePath.split('-')[filePath.split('-').length - 1]) + 1;
    filePath = logsDirPath + '/log-' + dayjs().format('YYYY-MM-DD') + '-' + num + '.txt';
    await fs.writeAsStringAsync(filePath, '', { encoding: 'utf8' });
  }
  console.log('writeAsStringAsync success');
};

export const getLogText = async () => {
  return await fs.readAsStringAsync(filePath, { encoding: 'utf8' });
};

export const getLogFilePath = () => {
  return filePath;
};

export const copyLogFileToDownload = async () => {
  const downloadPath = `${fs.documentDirectory}log-${dayjs().format('YYYY-MM-DD')}.txt`;
  await fs.copyAsync({ from: filePath, to: downloadPath });
  return downloadPath;
};
